package com.buli.blmall.admin.core.security.provider;

import com.buli.blmall.admin.common.service.SmsService;
import com.buli.blmall.admin.enums.LoginType;
import com.buli.blmall.admin.exception.LoginException;
import com.buli.blmall.admin.exception.error.LoginErrorCode;
import com.buli.blmall.admin.system.entity.SysUser;
import com.buli.blmall.admin.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ott.OneTimeTokenAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 短信验证码登录
 * @author xiang.gao
 * @date 2025/2/28 19:00
 */
@Component
public class PhoneSmsAuthProvider extends BaseAuthProvider {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SmsService smsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.isAuthenticated()) {
            return authentication;
        }
        String phoneNumber = (String) authentication.getPrincipal();
        String smsCode = (String) authentication.getCredentials();
        // 校验验证码（这里假设有一个方法 validateSmsCode）
        if (!smsService.verify(phoneNumber, smsCode)) {
            throw new BadCredentialsException("Invalid SMS code");
        }
        // 根据手机号查找用户
        SysUser sysUser = sysUserService.getByMobile(phoneNumber);
        if (sysUser == null) {
            throw new LoginException(LoginErrorCode.PHONE_NOT_EXIST);
        }
        return createAuthentication(LoginType.PASSWORD, phoneNumber, sysUser);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OneTimeTokenAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
